package it.ma.musicplayernew.fragment;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.Mpdam.Androggek.animation.AndrogeekAnimation;
import com.hxjr.dialog.DialogUtils;
import com.hxjr.dialog.SweetAlertDialog;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.skyfishjy.library.RippleBackground;
import com.zhongdao.swing.R;

import java.text.SimpleDateFormat;
import java.util.Date;

import app.akexorcist.bluetotohspp.library.BluetoothSPP;
import app.akexorcist.bluetotohspp.library.BluetoothState;
import it.ma.musicplayernew.API;
import it.ma.musicplayernew.ContentValues;
import it.ma.musicplayernew.MainActivity;
import it.ma.musicplayernew.holder.DeviceListHolder;
import it.ma.musicplayernew.modle.Track;
import it.ma.musicplayernew.service.CoreService;
import it.ma.musicplayernew.utils.CMDUtils;
import it.ma.musicplayernew.utils.DensityUtils;
import victor.view.FrameProgressBar;
import victor.view.victor.view.impl.OnProgressChangedListener;

/**
 * @包名: it.ma.musicplayernew.fragment
 * @作者: Victor
 * @创建时间 : 2015/9/14 15:37
 * @描述: TODO
 */
public class ControlPanelFragment2 extends Fragment implements CoreService.OnProgressChangeListener, DeviceListHolder.onDeviceSelectListener {

    public static final int OFF_MODE = 0;
    public static final int VOICE_MODE = 0; //声控
    public static final int MUSIC_MODE = 1; // mid
    public static final int USB_MODE = 2; //usb
    public static final int MOBILE_MODE = 3; //手机
    private int mMode = OFF_MODE;
    private boolean isPlay = false;

    private RelativeLayout mRootView;

    @ViewInject(R.id.iv_swing_level)
    private ImageView ivSwingLevel;

    @ViewInject(R.id.iv_play)
    private ImageView mIvPlay;

    @ViewInject(R.id.iv_timer_8)
    private ImageView ivTimer_8;
    @ViewInject(R.id.iv_timer_15)
    private ImageView ivTimer_15;
    @ViewInject(R.id.iv_timer_30)
    private ImageView ivTimer_30;

    @ViewInject(R.id.iv_mode_swing)
    private ImageView ivModeSwing;
    @ViewInject(R.id.iv_mode_usb)
    private ImageView ivModeUsb;
    @ViewInject(R.id.iv_mode_mobile)
    private ImageView ivModeMobile;

    @ViewInject(R.id.iv_water)
    private ImageView mIvWater;
    @ViewInject(R.id.iv_bird)
    private ImageView mIvBird;

    @ViewInject(R.id.progressbar)
    private SeekBar mProgressbar;
    @ViewInject(R.id.tv_total_time)
    private TextView mTvTotalTime;
    @ViewInject(R.id.tv_curr_time)
    private TextView mTvCurrTime;
    @ViewInject(R.id.ll_time)
    private View ll_time;

    @ViewInject(R.id.tv_status)
    private TextView textStatus;

    @ViewInject(R.id.fpb_vol)
    private FrameProgressBar mFpb;

    //声控显示水波界面
    @ViewInject(R.id.content_RippleBackground)
    private RippleBackground rippleBackground;

    @ViewInject(R.id.rl_content)
    private View rl_content;

    private AndrogeekAnimation mAndrogeekAnimation;

    /**
     * 摇摆级别
     */
    private int swingLevel = 0;

    /**
     * 定时状态
     */
    private int timeStatus = 0;

    /**
     * 声音大小
     */
    private int volStatus = 0;

    private int[] swing = {R.mipmap.sw_swing_0, R.mipmap.sw_swing_1, R.mipmap.sw_swing_2, R.mipmap.sw_swing_3, R.mipmap.sw_swing_4, R.mipmap.sw_swing_5, R.mipmap.sw_swing_6, R.mipmap.sw_swing_7, R.mipmap.sw_swing_8};

    private CoreService mServiceCallback;

    private SweetAlertDialog loadingDialog;
    private float currTime;
    private float totalTime;

    private BluetoothSPP bt;

    private void initBluetooth() {
        bt = new BluetoothSPP(getActivity());
        if(!bt.isBluetoothAvailable()) {
            Toast.makeText(getActivity().getApplicationContext()
                    , getString(R.string.bluetooth_not_available)
                    , Toast.LENGTH_SHORT).show();
            getActivity().finish();
        }

        bt.setOnDataReceivedListener(new BluetoothSPP.OnDataReceivedListener() {
            public void onDataReceived(byte[] data, String message) {
                int len = message.length();
                Log.e("onDataReceived", message + " len:" + len);
                String substring;
                int endIndex = 0;
                String[] split = message.split(API.BASE);
                for (String string : split) {
                    endIndex = string.indexOf(API.END_CHART);
                    if (endIndex > -1) {
                        substring = API.BASE + string.substring(0, endIndex);
                        if (ContentValues.D) Log.e("message", " read : " + substring);
                        //读取到数据
                        onReadMessage(substring);
                    }
                }
            }
        });

        bt.setBluetoothConnectionListener(new BluetoothSPP.BluetoothConnectionListener() {
            public void onDeviceDisconnected() {
                textStatus.setText(getString(R.string.not_connected));
//                menu.clear();
//                getMenuInflater().inflate(R.menu.menu_connection, menu);
            }

            public void onDeviceConnectionFailed() {
                textStatus.setText(getString(R.string.connection_failed));
            }

            public void onDeviceConnected(String name, String address) {
                //同步
                sendMessage(API.SYNC);
                textStatus.setText(getString(R.string.title_connected_to) + name);
//                textStatus.setText("Status : Connected to " + name);
//                menu.clear();
//                getMenuInflater().inflate(R.menu.menu_disconnection, menu);
            }
        });
        bt.setBluetoothStateListener(new BluetoothSPP.BluetoothStateListener() {
            @Override
            public void onServiceStateChanged(int state) {
                if (BluetoothState.STATE_CONNECTING == state) {
                    textStatus.setText(getString(R.string.title_connecting));
                }else if(BluetoothState.STATE_LISTEN == state){
                    textStatus.setText(getString(R.string.not_connected));
                }
            }
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        mRootView = (RelativeLayout) inflater.inflate(R.layout.control_panel_2, null);

        initBluetooth();

        return mRootView;
    }

    public void onDestroy() {
        super.onDestroy();

        if(bt.getServiceState() == BluetoothState.STATE_CONNECTED)
            bt.disconnect();

        bt.stopService();

        if(mDeviceListHolder != null) mDeviceListHolder.onDestroy();
    }

    public void onStart() {
        super.onStart();
        if (!bt.isBluetoothEnabled()) {
            Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(intent, BluetoothState.REQUEST_ENABLE_BT);
        } else {
            if(!bt.isServiceAvailable()) {
                bt.setupService();
                bt.startService(BluetoothState.DEVICE_OTHER);
                setup();
            }
        }
    }

    private void setup() {
        initView();
    }

    private void initView() {
        ViewUtils.inject(this, mRootView);
        mProgressbar.setEnabled(false);
        //声控模式波纹
        rippleBackground.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                rippleBackground.getParent().requestDisallowInterceptTouchEvent(true);
                return false;
            }
        });

        Integer[] arr = {
                R.mipmap.sw_vol_0,R.mipmap.sw_vol_1, R.mipmap.sw_vol_2, R.mipmap.sw_vol_3,
                R.mipmap.sw_vol_4, R.mipmap.sw_vol_5,R.mipmap.sw_vol_6,R.mipmap.sw_vol_7,
                R.mipmap.sw_vol_8,R.mipmap.sw_vol_9,R.mipmap.sw_vol_10
        };
        mFpb.setFrameResArray(arr);
        mFpb.setOnProgressChangedListener(new OnProgressChangedListener() {
            @Override
            public void onProgressChanged(View view, int currFrame, int totalFrame) {
                if (sendMessage(API.VOL + Integer.toHexString(currFrame).toString().toUpperCase())) {
                    volStatus = currFrame;
                } else {
                    mFpb.setLevel(volStatus);
                }
            }

            @Override
            public void onPostProgressChanged(View view, int currFrame, int totalFrame) {
                if (sendMessage(API.VOL + Integer.toHexString(currFrame).toString().toUpperCase())) {
                    volStatus = currFrame;
                } else {
                    mFpb.setLevel(volStatus);
                }
            }
        });

        initVoiceLayout();

        initDeviceListLayout();
    }

    private DeviceListHolder mDeviceListHolder;

    private void initDeviceListLayout() {
        mDeviceListHolder = new DeviceListHolder(getActivity());
        mDeviceListHolder.setOnDeviceSelectListener(this);
        mRootView.addView(mDeviceListHolder.getRootView());
        mAndrogeekAnimation = new AndrogeekAnimation.GuillotineBuilder(mDeviceListHolder.getRootView(),
                mDeviceListHolder.getRootView().findViewById(R.id.iv_menu_back),
                mRootView.findViewById(R.id.top_back1))
                .setStartDelay(100)
                .setActionBarViewForAnimation(mRootView.findViewById(R.id.head))
                .setClosedOnStart(true)
                .setAndrogeekListener(new AndrogeekListener())
                .build();
    }

    @Override
    public void onDeviceSelect(Intent data) {
        if(mAndrogeekAnimation != null) mAndrogeekAnimation.close();
        if(data != null && bt != null){
            bt.connect(data);
        }
    }

    public boolean onBackPressed() {
        if(mAndrogeekAnimation != null && mAndrogeekAnimation.isOpened()) {
            mAndrogeekAnimation.close();
            return true;
        }
        return false;
    }

    class AndrogeekListener implements com.Mpdam.Androggek.interfaces.AndrogeekListener{
        @Override
        public void onGuillotineOpened() {
            ((MainActivity)getActivity()).getSlidingMenu().setSlidingEnabled(false);
        }

        @Override
        public void onGuillotineClosed() {
            ((MainActivity)getActivity()).getSlidingMenu().setSlidingEnabled(true);
        }
    }

    private void initVoiceLayout() {
        mRootView.findViewById(R.id.iv_name).getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                mRootView.findViewById(R.id.iv_name).getViewTreeObserver().removeGlobalOnLayoutListener(this);
                int[] location = new int[2];
                mRootView.findViewById(R.id.iv_name).getLocationInWindow(location);
                int y1 = location[1];
                mRootView.findViewById(R.id.iv_doll).getLocationInWindow(location);
                int y2 = location[1];
                Log.i("location", "y1 = " + y1 + " y2 = " + y2);
                int dy = y2 - y1;
                if (dy > 0) {
//                    RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) rl_content.getLayoutParams();
//                    if (params == null) {
//                        params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
//                    }
//                    params.setMargins(0, 0, 0, dy * 2 + DensityUtils.dip2px(getActivity(),22));
//                    rl_content.setLayoutParams(params);
                    rl_content.setPadding(0, 0, 0, dy * 2 + DensityUtils.dip2px(getActivity(),22));
                }
                rl_content.setVisibility(View.GONE);
            }
        });

    }

    private void onReadMessage(String readMessage) {
        if (readMessage.startsWith(API.VOL)){
            //音量返回值
            try{
                int status = Integer.parseInt(readMessage.substring(API.VOL.length(), API.VOL.length() + 1), 16);
                updateVolStatus(status);
            }catch (Throwable t){
                t.printStackTrace();
            }

        } else if(readMessage.startsWith(API.TIME_RETURN)){
            //定时返回值
            try{
                int level = Integer.parseInt(readMessage.substring(API.TIME_RETURN.length(), API.TIME_RETURN.length() + 1));
                updateTimeStatus(level);
            }catch (Throwable t){
                t.printStackTrace();
            }

        } else if (readMessage.startsWith(API.RANGE_RETURN)) {
            //摆幅返回值
            try {
                int level = Integer.parseInt(readMessage.substring(API.RANGE_RETURN.length(), API.RANGE_RETURN.length() + 1));
                updateSwingLevel(level);
            } catch (Throwable t) {
                t.printStackTrace();
            }
        }else if(readMessage.startsWith(API.USB_MODE)){
            //正在usb模式
            updatePlayMode(USB_MODE);

            //隐藏加载对话框
            dismissDialog();
            dismissVoiceAnimation();

        }else if(readMessage.startsWith(API.MID_MODE)){
            //MID 模式
            updatePlayMode(MUSIC_MODE);

            if(isShowLoadingDialog()){
                //隐藏加载对话框
                dismissDialog();

                Toast.makeText(getActivity(),getString(R.string.switched_to_MID),Toast.LENGTH_LONG).show();
            }

            dismissVoiceAnimation();

        }else if(readMessage.startsWith(API.VOICE_MODE)
//                || readMessage.startsWith("AT#160")
                ){
            // 声控模式
            updatePlayMode(VOICE_MODE);
            //弹对话框
            showVoiceAnimation();
        }else if(readMessage.startsWith(API.BT_MODE)){
            // BT模式
            updatePlayMode(MOBILE_MODE);

            if(isShowLoadingDialog()){
                //隐藏加载对话框
                dismissDialog();

                Toast.makeText(getActivity(),getString(R.string.switched_to_BT),Toast.LENGTH_LONG).show();
            }

            dismissVoiceAnimation();
        }else if(readMessage.startsWith(API.TOTAL_TIME)){
            //音乐总时间
            String readMusicTime = CMDUtils.readMusicTime(readMessage);
            mTvTotalTime.setText(readMusicTime);
            totalTime = CMDUtils.parseTime(readMessage);
            updatePosition();
            //隐藏加载对话框
            dismissDialog();

        }else if(readMessage.startsWith(API.CURR_TIME)){
            //当前时间
            String readMusicTime = CMDUtils.readMusicTime(readMessage);
            mTvCurrTime.setText(readMusicTime);
            currTime = CMDUtils.parseTime(readMessage);
            updatePosition();
            //隐藏加载对话框
            dismissDialog();
        }

    }


    /**
     * 更新进度
     */
    private void updatePosition() {
        if (currTime > totalTime) {
            mProgressbar.setProgress(0);
        }

        Log.d("updatePosition", "totalTime : " + totalTime + " currTime ：" + currTime);

        int position = (int) (((currTime * 1.0f) / totalTime) * 100);
        mProgressbar.setProgress(position);
    }

    private void showVoiceAnimation() {
        rippleBackground.startRippleAnimation();
        rl_content.setVisibility(View.VISIBLE);
    }

    private void dismissVoiceAnimation() {
        rippleBackground.stopRippleAnimation();
        rl_content.setVisibility(View.GONE);
    }

    /**
     * 设置音乐播放服务
     * @param serviceCallback
     */
    public void setServiceCallback(CoreService serviceCallback){
        mServiceCallback = serviceCallback;

        mServiceCallback.setProgressListener(this);

        Log.i("nick", mServiceCallback.toString());
    }

    /*@OnCompoundButtonCheckedChange(R.id.ib_usb)
    public void usb(CompoundButton compoundButton, boolean b){
        if(b){
            compoundButton.setClickable(false);
            updatePlayMode(USB_MODE);
        }else{
            compoundButton.setClickable(true);
        }
    }*/
    @OnClick(R.id.iv_switch_mode)
    public void switchMode(View view){

        sendMessage(API.MODE);

        /*int mode = (mMode + 1) % 4; //循环切换下一模式

        if(mode == VOICE_MODE){
            mode = 1;
        }

        if(mode == MUSIC_MODE){
            music(view);
        }else if(mode == USB_MODE){
            updatePlayMode(USB_MODE);
        }else if(mode == MOBILE_MODE){
            ToBTMode();
        }*/

//        if(mMode != USB_MODE)
//            updatePlayMode(USB_MODE);
    }

    /**
     * 切换模式
     * @param mode
     */
    public boolean updatePlayMode(int mode) {
        boolean result = false;
        if(mode == USB_MODE){
            if(mServiceCallback != null && mServiceCallback.getIsPlaying()){
                mServiceCallback.pausePlayer();
            }
            if(!sendMessage(API.USB_MODE)){
                //mIbUsb.setChecked(false);
                //mIbUsb.setClickable(true);
            }else{
                if(mMode != USB_MODE){
                    mMode = USB_MODE;
                    showLoading();
                }
                result = true;
                //切换模式后 默认为 播放状态
                updateControlButtonBackground(true);
            }
        }else if(mode == MUSIC_MODE){
            if(mServiceCallback != null && mServiceCallback.getIsPlaying()){
                mServiceCallback.pausePlayer();
            }
            if(sendMessage(API.MID_MODE)){
                //mIbUsb.setChecked(false);
                result = true;
                mMode = MUSIC_MODE;
                //切换模式后 默认为 播放状态
                updateControlButtonBackground(true);
            }
        }else if(mode == VOICE_MODE){
            //mIbUsb.setChecked(false);
//            if(mServiceCallback != null && mServiceCallback.getIsPlaying()){
//                mServiceCallback.pausePlayer();
//            }
            result = true;
            mMode = VOICE_MODE;
            //切换模式后 默认为 播放状态
            updateControlButtonBackground(false);

        }else if(mode == MOBILE_MODE){
            result = sendMessage(API.BT_KEY);
            if(result){
                //mIbUsb.setChecked(false);
                mMode = MOBILE_MODE;
            }
        }

        updateModeDisplay(mMode);

        return result;
    }

    /**
     * 更新模式显示
     */
    public void updateModeDisplay(int mode) {
        mMode = mode;

        ivModeSwing.setImageResource(mMode == MUSIC_MODE ? R.mipmap.sw_swing_mode_on : R.mipmap.sw_swing_mode_off);
        ivModeUsb.setImageResource(mMode == USB_MODE ? R.mipmap.sw_usb_mode_on : R.mipmap.sw_usb_mode_off);
        ivModeMobile.setImageResource(mMode == MOBILE_MODE ? R.mipmap.sw_bluetooth_mode_on : R.mipmap.sw_bluetooth_mode_off);

        mIvWater.setEnabled(mMode == MUSIC_MODE);
        mIvBird.setEnabled(mMode == MUSIC_MODE);

        mTvTotalTime.setText("00:00");
        mTvCurrTime.setText("00:00");
        //初次化进度
        totalTime = 0;
        currTime = 0;
        mProgressbar.setProgress(0);

        if(mMode == USB_MODE || mMode == MOBILE_MODE){
            ll_time.setVisibility(View.VISIBLE);
            mProgressbar.setVisibility(View.VISIBLE);
        }else{
            ll_time.setVisibility(View.INVISIBLE);
            mProgressbar.setVisibility(View.INVISIBLE);
        }
    }

    private boolean sendMessage(String msg) {
        if (ContentValues.D) Log.e("message", " send : " + msg);
        if(bt == null){
            initBluetooth();
        }
        if(bt.getServiceState() != BluetoothState.STATE_CONNECTED
                && bt.getServiceState() != BluetoothState.STATE_CONNECTING){
            bt.setDeviceTarget(BluetoothState.DEVICE_OTHER);
            if(((MainActivity)getActivity()).getSlidingMenu().isMenuShowing()){
                ((MainActivity)getActivity()).getSlidingMenu().showContent(true);
            }
            if(mAndrogeekAnimation != null) mAndrogeekAnimation.open();
            if(mDeviceListHolder != null) mDeviceListHolder.setData(null);
//            Intent intent = new Intent(getActivity(), DeviceList.class);
//            startActivityForResult(intent, BluetoothState.REQUEST_CONNECT_DEVICE);
        }
        return bt.send(msg, false);
    }

    private void showLoading() {
        loadingDialog = DialogUtils.getInstance().createLoadingDialog(getActivity(), getString(R.string.read_usb_data));

        loadingDialog.setCanceledOnTouchOutside(false);

        loadingDialog.setCancelable(true);

        loadingDialog.show();

    }
    private void dismissDialog() {
        if (loadingDialog != null && loadingDialog.isShowing()) {
            try {
                loadingDialog.cancel();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private boolean isShowLoadingDialog(){
        return loadingDialog != null && loadingDialog.isShowing();
    }

    @OnClick(R.id.iv_voice)
    public void voice(View view){
        if(sendMessage(API.VOICE_KEY)){
            updatePlayMode(VOICE_MODE);
            //startActivityForResult(new Intent(this.getActivity(), VoiceActivity.class), 111);
        }
    }

    @OnClick(R.id.rl_content)
    public void stopVoice(View view){
        if(sendMessage(API.VOICE_KEY)){
            updatePlayMode(VOICE_MODE);
        }
    }

    @OnClick(R.id.iv_toy)
    public void toy(View view){
        sendMessage(API.TOY_KEY);
    }

    @OnClick(R.id.iv_water)
    public void water(View view){
        sendMessage(API.WATER_KEY);
    }

    @OnClick(R.id.iv_bird)
    public void bird(View view){
        sendMessage(API.BIRD_KEY);
    }

    @OnClick(R.id.iv_to_swing_mode)
    public void music(View view){
        updatePlayMode(MUSIC_MODE);
    }

    @OnClick(R.id.iv_swing_plus)
    public void swingPlus(View view) {
        if(swingLevel < swing.length - 1){
            int temp = swingLevel + 1;
            if(sendMessage(API.NEXT_SET + temp)){
                updateSwingLevel(temp);
            }
        }
    }

    @OnClick(R.id.iv_swing_minus)
    public void swingMinus(View view) {
        int temp = 0;
        if(swingLevel > 0){
            temp = swingLevel - 1;
        }
        if(sendMessage(API.PREV_SET + temp)){
            updateSwingLevel(temp);
        }
    }

    @OnClick(R.id.iv_vol_plus)
    public void volPlus(View view){
        if(mFpb != null){
            mFpb.setLevel1(volStatus + 1);
        }else{
            initBluetooth();
        }
    }

    @OnClick(R.id.iv_vol_minus)
    public void volMinus(View view){
        if(mFpb != null){
            mFpb.setLevel1(volStatus - 1);
        }else{
            initBluetooth();
        }
    }

    /**
     * 更新摆幅级别
     * @param level
     */
    private void updateSwingLevel(int level) {
        swingLevel = level;
        ivSwingLevel.setImageResource(swing[swingLevel]);
    }

    @OnClick(R.id.iv_timer)
    public void timer(View view) {
        int temp = (timeStatus + 1) % 4;
        if(sendMessage(API.T_SET + temp)){
            updateTimeStatus(temp);
        }
    }

    private void updateTimeStatus(int status) {
        timeStatus = status;
        ivTimer_8.setImageResource(timeStatus > 0 ? R.mipmap.sw_timer_on : R.mipmap.sw_timer_off);
        ivTimer_15.setImageResource(timeStatus > 1 ? R.mipmap.sw_timer_on : R.mipmap.sw_timer_off);
        ivTimer_30.setImageResource(timeStatus > 2 ? R.mipmap.sw_timer_on : R.mipmap.sw_timer_off);
    }

   /* @OnClick(R.id.audio_add)
    public void addAudio(View view) {
        if (volStatus < audio.length - 1) {
            int temp = volStatus + 1;
            if(sendMessage(API.VOL + Integer.toHexString(temp).toString().toUpperCase())){
                updateVolStatus(temp);
            }
        }
    }*/

    private void updateVolStatus(int status) {
        mFpb.setLevel(status);
        volStatus = status;
//        iv_audio.setImageDrawable(getActivity().getResources().getDrawable(audio[volStatus]));
    }

    /*@OnClick(R.id.audio_sub)
    public void subAudio(View view) {
        if (volStatus > 0) {
            int temp = volStatus - 1;
            if(sendMessage(API.VOL + Integer.toHexString(temp).toString().toUpperCase())){
                updateVolStatus(temp);
            }
        }
    }*/

    @OnClick(R.id.top_back)
    public void toggle(View view){
        ((MainActivity)getActivity()).getSlidingMenu().toggle();
    }

    public void onPlayUpdate(Track track){
        if(mMode == MOBILE_MODE){
            updateControlButtonBackground(mServiceCallback != null && mServiceCallback.getIsPlaying());
        }
    }
    /**
     * 更新播放按钮显示
     */
    public void updateControlButtonBackground(boolean isPlay) {
        this.isPlay = isPlay;
        mIvPlay.setImageResource(this.isPlay ? R.mipmap.sw_icon_pause : R.mipmap.sw_icon_play);
    }

    @OnClick(R.id.iv_play)
    public void play(View view){
        if(mMode == OFF_MODE){
            sendMessage(API.SYNC);
            return;
        }

        if(mMode != MOBILE_MODE){
            boolean isPlay = !this.isPlay;
            sendMessage(isPlay ? API.PLAY : API.PAUSE);
            updateControlButtonBackground(isPlay);
        }else {
            //BT
            ToBTMode();
        }
    }

    private void ToBTMode() {
        if(mServiceCallback == null){
            return;
        }
        updatePlayMode(MOBILE_MODE);
        if (mServiceCallback.getIsPlaying()) {
            mServiceCallback.pausePlayer();
        } else {
            mServiceCallback.resumePlayer();
        }
    }

    @OnClick(R.id.iv_pre)
    public void previous(View view){
        if(mMode == OFF_MODE){
            sendMessage(API.SYNC);
            return;
        }
        if(mMode != MOBILE_MODE){
            sendMessage(API.PREV);
            updateControlButtonBackground(true);
        }else {
            if (mServiceCallback == null) {
                return;
            }
            updatePlayMode(MOBILE_MODE);
            mServiceCallback.playPreviousTrack();
        }
    }

    @OnClick(R.id.iv_next)
    public void next(View view){
        if(mMode == OFF_MODE){
            sendMessage(API.SYNC);
            return;
        }
        if(mMode != MOBILE_MODE){
            sendMessage(API.NEXT);
            updateControlButtonBackground(true);
        }else {
            if (mServiceCallback == null) {
                return;
            }
            updatePlayMode(MOBILE_MODE);
            mServiceCallback.playNextTrack();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.d("onActivityResult" , "onActivityResult");
//        if(requestCode == 111){
//            //退出声控模式
//            sendMessage(API.VOICE_KEY);
//        }
        if(requestCode == BluetoothState.REQUEST_CONNECT_DEVICE) {
            if(resultCode == Activity.RESULT_OK)
                bt.connect(data);
        } else if(requestCode == BluetoothState.REQUEST_ENABLE_BT) {
            if(resultCode == Activity.RESULT_OK) {
                bt.setupService();
                bt.startService(BluetoothState.DEVICE_OTHER);
                setup();
                goToSetting();
            } else {
                Toast.makeText(getActivity()
                        , getString(R.string.bluetooth_not_available)
                        , Toast.LENGTH_SHORT).show();
                getActivity().finish();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 去设置页面
     */
    private void goToSetting() {
        startActivity(new Intent(Settings.ACTION_BLUETOOTH_SETTINGS));//直接进入手机中的蓝牙设置界面
    }

    SimpleDateFormat dateFormat = new SimpleDateFormat("mm:ss");
    @Override
    public void onProgressChange(int currentPosition, int duration) {
        String currTime = dateFormat.format(new Date(currentPosition));
        String totalTime = dateFormat.format(new Date(duration));

        Log.i("onProgressChange", "currentPosition : " + currTime
                + " duration : " + totalTime);
        if(mMode == MOBILE_MODE){
            mTvCurrTime.setText(currTime);
            mTvTotalTime.setText(totalTime);
            this.currTime = (float) currentPosition + 0.0f;
            this.totalTime = (float) duration + 0.0f;
            updatePosition();
        }
    }


    /*private SweetAlertDialog callDialog;
    @OnClick(R.id.tv_server_number)
     public void callServer(View view){
        callDialog = DialogUtils.getInstance().createNormDialog(getActivity(), "服务热线：400-801-3819");
        callDialog.setCanceledOnTouchOutside(true);
        callDialog.setCancelable(true);
        callDialog.setCancelText("取消");
        callDialog.setConfirmText("拨打电话");
        callDialog.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
            @Override
            public void onClick(SweetAlertDialog sweetAlertDialog) {
                callDialog.cancel();
                //用intent启动拨打电话
                Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:4008013819"));
                startActivity(intent);
            }
        });
        callDialog.show();
    }

    @OnClick(R.id.tv_website)
    public void viewWebsite(View view){
        callDialog = DialogUtils.getInstance().createNormDialog(getActivity(), "公司网站：www.togyibaby.com");
        callDialog.setCanceledOnTouchOutside(true);
        callDialog.setCancelable(true);
        callDialog.setCancelText("取消");
        callDialog.setConfirmText("打开网站");
        callDialog.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
            @Override
            public void onClick(SweetAlertDialog sweetAlertDialog) {
                callDialog.cancel();
                //用intent打开网站
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.togyibaby.com"));
                startActivity(intent);
            }
        });
        callDialog.show();
    }*/


}
